from services import SparkApi

# 用于配置大模型版本，默认“general/generalv2”
# domain = "general"  # v1.5版本
domain = "generalv2"  # v2.0版本
# 云端环境的服务地址
# Spark_url = "ws://spark-api.xf-yun.com/v1.1/chat"  # v1.5环境的地址
Spark_url = "ws://spark-api.xf-yun.com/v2.1/chat"  # v2.0环境的地址


def getLength(text):
    """
    计算会话中总字数
    :param text: 会话列表
    :return: 总字数
    """
    length = 0
    for content in text:
        temp = content["content"]
        contentLength = len(temp)
        length += contentLength
    return length


def checkLength(text):
    """
    控制会话总字数小于等于8000，超过的话就删除会话记录中最早的一条，直到满足字数要求。
    :param text: 会话列表
    :return: 总字数小于等于8000的会话列表
    """
    while getLength(text) > 8000:
        del text[0]
    return text


class SparkClient:
    def __init__(self, appid, api_key, api_secret):
        self.appid = appid
        self.api_key = api_key
        self.api_secret = api_secret
        self.conversations = []

    def _buildConversations(self, role, content):
        jsonContent = {"role": role, "content": content}
        self.conversations.append(jsonContent)
        return self.conversations

    def chat(self, message):
        question = checkLength(self._buildConversations("user", message))
        answer = SparkApi.main(self.appid, self.api_key, self.api_secret, Spark_url, domain, question)
        self._buildConversations("assistant", answer)
        return answer
